package net.esj.basic.view;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.esj.basic.core.engine.config.MelonConfig;
import net.esj.basic.core.view.ResponseStatusCode;
import net.esj.basic.core.view.filter.BackUrlFilter;
import net.esj.basic.core.view.filter.BackUrlFilter.BackUri;
import net.esj.basic.core.view.filter.I18NFilter;
import net.esj.basic.core.view.tools.ActionContext;
import net.esj.basic.pojo.system.UserRule;
import net.esj.basic.service.provider.UserRuleProvider;
import net.esj.basic.utils.StringUtils;
import net.esj.basic.utils.view.BaseJsonMessage;
import net.esj.basic.utils.view.BaseJsonMessage.MessageLevel;
import net.esj.basic.utils.writer.SignImpl;
import net.esj.basic.utils.writer.Signed;
import net.esj.basic.utils.writer.WriteException;
import net.esj.basic.utils.writer.Writer;
import net.esj.basic.utils.writer.WriterCode;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.util.Assert;

public class BaseAction extends SpringDependActionSupport implements ResponseStatusCode{
	
	protected static final Logger logger = Logger.getLogger(BaseAction.class);
	
	public static final String LIST = "list";
	public static final String FORM = "form";
	public static final String RELOAD = "reload";
	public static final String GLOBAL_ERROR= "globalerror";
	public static final String SCRIPT = "script";
	
	protected Writer writer;
	
	private String action_id;
	
	public String init() throws Exception {
		return SUCCESS;
	}

	protected HttpSession getSession(){
		return ServletActionContext.getRequest().getSession();
	}
	
	protected <T> T getSessionObject(String key,Class<T> clazz){
		return (T) getSession().getAttribute(key);
	}
	
	protected HttpServletRequest getRequest(){
		return ServletActionContext.getRequest();
	}
	
	protected HttpServletResponse getResponse(){
		return ServletActionContext.getResponse();
	}
	
	protected void writeJson(Object o){
		writeJson(o, new String[]{});
	}
	
	protected void writeJson(Object o,String contentType){
		writeJson(o, contentType,new String[]{});
	}
	
	protected void writeJson(Object o,String... groups){
		writeJson(o,"text",WriterCode.NULL,groups);
	}
	
	protected void writeJson(Object o,WriterCode code,String... groups) {
		writeJson(o,"text",code,groups);
	}
	
	protected void writeJson(Object o,String contentType,String... groups){
		writeJson(o,contentType,WriterCode.NULL,groups);
	}
	
	protected void writeJson(Object o,String contentType,WriterCode code,String... groups) {
		PrintWriter out =null;
		getResponse().setContentType("text/"+contentType+";charset=UTF-8");
		String result = null;
		try {
			if(groups!=null && groups.length>0){
				Signed signed = new SignImpl(groups);
				result = writer.write(o, signed, code);
			}else{
				result = writer.write(o, code);
			}
			out = getResponse().getWriter();
			out.print(result);
			logger.debug(result);
			System.out.println(result);
		} catch (WriteException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if (out != null) {
				out.close();
			}
		}
	}
	
	protected void writeString(String str) {
		PrintWriter out =null;
		getResponse().setContentType("text/text;charset=UTF-8");
		try {
			out = getResponse().getWriter();
			out.print(str);
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if (out != null) {
				out.close();
			}
		}
	}
	
	protected void writeError(Object o,int responseStatus){
		PrintWriter out =null;
		getResponse().setContentType("text/text;charset=UTF-8");
		getResponse().setStatus(responseStatus);
		try {
			String result = writer.write(o, WriterCode.NULL);
			out = getResponse().getWriter();
			out.print(result);
		} catch (WriteException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if (out != null) {
				out.close();
			}
		}
	}
	
	protected void writeError(String str ,int responseStatus){
		PrintWriter out =null;
		getResponse().setContentType("text/text;charset=UTF-8");
		getResponse().setStatus(responseStatus);
		try {
			out = getResponse().getWriter();
			out.print(str);
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if (out != null) {
				out.close();
			}
		}
	}
	
	protected void writeError(String str){
		writeError(str, RESPONSE_STATUS_NORMAL_ERROR);
	}
	
	protected void writeError(Object obj){
		writeError(obj, RESPONSE_STATUS_NORMAL_ERROR);
	}
	
	protected void writeValidateError(Object o){
		writeError(o, RESPONSE_STATUS_VALIDATE_ERROR);
	}
	
	protected void writeValidateError(String str){
		writeError(str, RESPONSE_STATUS_VALIDATE_ERROR);
	}
	
	protected void writeBaseJsonMessage(String title,String msg,MessageLevel level,String contentType){
		BaseJsonMessage bjm = new BaseJsonMessage(title, msg, level);
		writeJson(bjm,contentType,new String[]{});
	}
	protected void writeBaseJsonMessage(String title,String msg,MessageLevel level){
		BaseJsonMessage bjm = new BaseJsonMessage(title, msg, level);
		writeJson(bjm);
	}
	
	protected void writeBaseJsonMessage(String msg,MessageLevel level){
		BaseJsonMessage bjm = new BaseJsonMessage(msg, level);
		writeJson(bjm);
	}
	
	protected void writeBaseJsonMessage(String title,String msg){
		BaseJsonMessage bjm = new BaseJsonMessage(title, msg);
		writeJson(bjm);
	}
	
	protected void writeBaseJsonMessage(String msg){
		BaseJsonMessage bjm = new BaseJsonMessage(msg);
		writeJson(bjm);
	}
	
	protected <T> T getSessionUser(Class<T> clazz){
		UserRule rule = UserRuleProvider.getUserRule(clazz);
		if(rule!=null){
			return (T) getSession().getAttribute(rule.getSessionKey());
		}
		return null;
	}
	
	protected String getNormalWebAddress(){
		return "http://"+getRequest().getServerName()+":"+getRequest().getServerPort()+getRequest().getContextPath();
	}
	
	protected Locale getCurrentLocale(){
		Locale local = (Locale) getSession().getAttribute(I18NFilter.STRUTS_I18N_KEY);
		if(local==null){
			local = ActionContext.getLocale();
		}
		return local;
	}
	
	public String getRemoteIp(){
		return ActionContext.getClient().getIp();
	}
	
	public String getBackURI(){
		BackUri uri =(BackUri)getSession().getAttribute(BackUrlFilter.BACK_URL);
		Assert.notNull(uri,"当前不支持getBackURI方法,请核查是否配置["+BackUrlFilter.class.getName()+"]拦截");
		return uri.getBackURI();
	}


	public String getAction_id(){
		if(!StringUtils.hasText(action_id)){
			action_id = Integer.toHexString(hashCode());
		}
		return action_id;
	}

	public void setAction_id(String action_id) {
		this.action_id = action_id;
	}

	public long getTimeMillis(){
		return System.currentTimeMillis();
	}
	
	@Inject
	public void setWriter(Writer writer) {
		this.writer = writer;
	} 
}
